﻿using ConmonDateModel;
using ConmonDateModel.ResponseBase;
using DateDBControl;
using DateDBControl.Model;
using DateDBControl.Redies;
using MyLogProject;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ServiceControl.Helps;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ServiceControl
{
    public static  class AppDataServiceControl
    {
        private static SqlManageControl SqlModel { set; get; }

       

        static AppDataServiceControl()
        {
            SqlModel = new SqlManageControl();
          
        }

 
        #region New
        public static void CreatDb() 
        {
            string _creatCompanySql = SqlsControl.CreatCompanyDb();
            int Companyresult = SqlModel.ExeCuteCommonSql(_creatCompanySql);
            if (Companyresult == -1)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "CreatDb", $"表{ComnonStaticModel.CompanyName}状态判定失败！");
            }

            string _creatAuthorizeSql = SqlsControl.CreatDeviceDb();
            int Authorizeresult = SqlModel.ExeCuteCommonSql(_creatAuthorizeSql);
            if (Authorizeresult == -1)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "CreatDb", $"表{ComnonStaticModel.DeviceDbName}状态判定失败！");
            }

            string _creatModuleDbSql = SqlsControl.CreatModeuleDb();
            int resultModuleDb = SqlModel.ExeCuteCommonSql(_creatModuleDbSql);
            if (resultModuleDb == -1)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "JudgeDeviceTimeByLastDay", $"表{ComnonStaticModel.ModeuleDbName}状态判定失败！");
            }

            string _creatHistoryModuleDbSql = SqlsControl.CreatHistoryModeuleDb();
            int resultHistoryModuleDb = SqlModel.ExeCuteCommonSql(_creatHistoryModuleDbSql);
            if (resultHistoryModuleDb == -1)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "JudgeDeviceTimeByLastDay", $"表{ComnonStaticModel.HistoryModeuleDbName}状态判定失败！");
            }

            string _creatuserDbSql = SqlsControl.CreatUserDb();
            int resultuserDb = SqlModel.ExeCuteCommonSql(_creatuserDbSql);
            if (resultuserDb == -1)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "JudgeDeviceTimeByLastDay", $"表{ComnonStaticModel.UserDbName}状态判定失败！");
            }

            string _creatRoleDbSql = SqlsControl.CreatRoleDb();
            int resultRoleDb = SqlModel.ExeCuteCommonSql(_creatRoleDbSql);
            if (resultRoleDb == -1)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "JudgeDeviceTimeByLastDay", $"表{ComnonStaticModel.RoleDbName}状态判定失败！");
            }

            string _creatmodelDbSql = SqlsControl.CreatDeviceModuleDb();
            int resultModellDb = SqlModel.ExeCuteCommonSql(_creatmodelDbSql);
            if (resultModellDb == -1)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "JudgeDeviceTimeByLastDay", $"表{ComnonStaticModel.DeviceModeuleDbName}状态判定失败！");
            }

            string _creatLoglDbSql = SqlsControl.CreaLogDb();
            int resultLogDb = SqlModel.ExeCuteCommonSql(_creatLoglDbSql);
            if (resultLogDb == -1)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "JudgeDeviceTimeByLastDay", $"表{ComnonStaticModel.RecodLogName}状态判定失败！");
            }
        }

        #region 所有模块操作

        public static ResponseBody ToAddTargetModule(string _uuid,string _moduleName, string version) 
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _addSql = SqlsControl.GetAddTargetModule(_uuid, _moduleName, version);
                var result = SqlModel.ExecuteNonQuery(_addSql);
                if (result > 0)
                {
                    rsult.Code = ErrorCode.OK;
                }
            }
            catch (Exception ex) 
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToDeleteTargetModule(string _uuid)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _addSql = SqlsControl.GetDeleteTargetModule(_uuid);
                var result = SqlModel.ExecuteNonQuery(_addSql);
                if (result > 0)
                {
                    rsult.Code = ErrorCode.OK;
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToGetAllModule(string _deviceid, string modulename)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _Sql = SqlsControl.GetAllModule(_deviceid, modulename);
           
                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                IList<ModuleManagerModel> resultList = ModelConvertHelper<ModuleManagerModel>.ConvertToModel(_dataSet);
                if (resultList.Count > 0)
                {
                    rsult.Code = ErrorCode.OK;
                    rsult.Data = JsonConvert.SerializeObject(resultList).JsonFormatOut();
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }

        #endregion

        #region 用户
        public static ResponseBody ToAddUser(UserModel usermodel)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                usermodel.password = GetMD5(usermodel.password);
                usermodel.password = GetMD5(usermodel.password);
                string _addSql = SqlsControl.GetAddUser(usermodel);
                var result = SqlModel.ExecuteNonQuery(_addSql);
                if (result > 0)
                {
                    rsult.Code = ErrorCode.OK;
                    rsult.Data= JsonConvert.SerializeObject(usermodel).JsonFormatOut();
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }

        public static ResponseBody ToCheckLimitByRole(string methodname, string _role) 
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _Sql = SqlsControl.GetTargetUserRole(_role);
                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                IList<RoleManagerMode> resultList = ModelConvertHelper<RoleManagerMode>.ConvertToModel(_dataSet);
                bool itemExits = resultList.Any(p => p.method == methodname);
                rsult.Code = itemExits?ErrorCode.OK: ErrorCode.CommonError;
                rsult.Description = itemExits ? "" : "无权访问";
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.Unknown;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToGetTargetUser(string username, string password)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _Sql = SqlsControl.GetTargetUser(username,password);

                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                IList<UserModel> resultList = ModelConvertHelper<UserModel>.ConvertToModel(_dataSet);
                if (resultList.Count > 0)
                {
                    var itemExitsUser = resultList.FirstOrDefault();
                    if (itemExitsUser != null)
                    {
                        string _pwd = GetMD5(password);
                        _pwd = GetMD5(_pwd);
                        if (_pwd == itemExitsUser.password)
                        {
                            var tInfo = TokenHelper.SetTokenInfo(username, password, itemExitsUser.role);
                            string Token = TokenHelper.GetToken(tInfo);
                            itemExitsUser.token = Token;
                            rsult.Code = ErrorCode.OK;
                            rsult.Data=JsonConvert.SerializeObject(itemExitsUser).JsonFormatOut();
                        }
                        else
                        {
                            rsult.Code = ErrorCode.CommonError;
                            rsult.Description = "密码错误";
                        }
                    }
                    else
                    {
                        rsult.Code = ErrorCode.CommonError;
                        rsult.Description = "密码错误";
                    }
                }
                else 
                {
                    rsult.Code = ErrorCode.CommonError;
                    rsult.Description = "用户不存在";
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }



        private static string GetMD5(string _pwd)
        {
            string _md5Str = "";
            try
            {
                using (var md5Hasher = MD5.Create())
                {
                    byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(_pwd));

                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < data.Length; i++)
                    {
                        sb.Append(data[i].ToString("x2"));
                    }
                    _md5Str = sb.ToString();
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetMD5", ex.ToString());
            }
            return _md5Str;
        }
        #endregion



        #region 公司操作
        public static ResponseBody ToGetAllCompanyNum()
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                var _itemResult = new ResulContentModel();
                string _AllCOuntSql = SqlsControl.GetCompanyAllCount();
                var item = new DateCountModel();
                item.Count = SqlModel.GetCommonDateCount(_AllCOuntSql);
                rsult.Code = ErrorCode.OK;
                rsult.Data = JsonConvert.SerializeObject(item).JsonFormatOut();
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToAddTargetCompany(string _code,string _uuid, string _companyname, string _linkman, string _linkPhone, string _description, string _token)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                var _Result = ApiActionAuth.OnAuthorization(_token);
                if (_Result.Code == ErrorCode.OK)
                {
                    UserModel itemUser = _Result.Data as UserModel;
                    string _addSql = SqlsControl.GetAddCompany(_code, _uuid, _companyname, _linkman, _linkPhone, _description, itemUser.username);
                    var result = SqlModel.ExecuteNonQuery(_addSql);
                    if (result > 0)
                    {
                        rsult.Code = ErrorCode.OK;
                    }
                }
                else 
                {
                    rsult.Code = ErrorCode.CommonError;
                    rsult.Description = "解析Token出错";
                }
                
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }

        public static ResponseBody ToUpdateTargetCompany(string _code, string _uuid, string _companyname, string _linkman, string _linkPhone, string _description, string _token)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                var _Result = ApiActionAuth.OnAuthorization(_token);
                if (_Result.Code == ErrorCode.OK) 
                {
                    UserModel itemUser = _Result.Data as UserModel;
                    string _addSql = SqlsControl.GetUpdatedCompany(_code, _uuid, _companyname, _linkman, _linkPhone, _description, itemUser.username);
                    var result = SqlModel.ExecuteNonQuery(_addSql);
                    if (result > 0)
                    {
                        rsult.Code = ErrorCode.OK;
                    }
                }
                else
                {
                    rsult.Code = ErrorCode.CommonError;
                    rsult.Description = "解析Token出错";
                }

            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }

        public static ResponseBody ToDeleteTargetCompany( string _uuid,bool _isClear)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _addSql = SqlsControl.GetDeleteCompany(_uuid);
                var result = SqlModel.ExecuteNonQuery(_addSql);
                if (result > 0)
                {
                    rsult.Code = ErrorCode.OK;
                    if (_isClear)
                    {
                        string _DelDeviceSql = SqlsControl.GetDeleteDeviceByCompany(_uuid);
                        var _DelDeviceResult = SqlModel.ExecuteNonQuery(_DelDeviceSql);
                        if (_DelDeviceResult<=0)
                        {
                            rsult.Code = ErrorCode.CommonError;
                        }
                    }                    
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToGetCompanyByPage(string companycode, string companyname,int inputpageCode, int inputPageSize)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                var _itemResult = new ResulContentModel();
                string _AllCOuntSql = SqlsControl.GetCompanyAllCount(companycode, companyname);
                var _AlldataSet = SqlModel.ExecuteQuery(_AllCOuntSql);
                IList<CompanyManagerModel> resultList = ModelConvertHelper<CompanyManagerModel>.ConvertToModel(_AlldataSet);
                //计算页数
                _itemResult.count= resultList.Count;


                string _Sql = SqlsControl.GetCompanyByPage(companycode, companyname,inputpageCode, inputPageSize);

                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                IList<CompanyManagerModel> resultPageList = ModelConvertHelper<CompanyManagerModel>.ConvertToModel(_dataSet);
                _itemResult.Items= resultPageList;
                rsult.Code = ErrorCode.OK;
                rsult.Data = JsonConvert.SerializeObject(_itemResult).JsonFormatOut();
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToGetCompanyBySearch(string _code, string _companyname)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _Sql = SqlsControl.GetCompanyBSearch(_code, _companyname);

                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                IList<CompanyManagerModel> resultList = ModelConvertHelper<CompanyManagerModel>.ConvertToModel(_dataSet);
                rsult.Code = ErrorCode.OK;
                rsult.Data = JsonConvert.SerializeObject(resultList).JsonFormatOut();
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }
        #endregion


        #region 设备操作

        public static ResponseBody ToGetAllDeviceNum()
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                var _itemResult = new ResulContentModel();
                string _AllCOuntSql = SqlsControl.GetAllDeviceCount();
                var item = new DateCountModel();
                item.Count = SqlModel.GetCommonDateCount(_AllCOuntSql);
                rsult.Code = ErrorCode.OK;
                rsult.Data = JsonConvert.SerializeObject(item).JsonFormatOut();
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }

        public static ResponseBody ToAddDeviceByCompany(string _uuid, string _companyid,string _devicename, string _robatmac, string _license,DateTime? _effecttime,string _token)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                var _Result = ApiActionAuth.OnAuthorization(_token);
                if (_Result.Code == ErrorCode.OK)
                {
                    UserModel itemUser = _Result.Data as UserModel;
                    string _addSql = SqlsControl.GetAddDevicByCompany(_uuid, _companyid, _devicename, _robatmac, _license, _effecttime, itemUser.username);
                    var result = SqlModel.ExecuteNonQuery(_addSql);
                    if (result > 0)
                    {
                        rsult.Code = ErrorCode.OK;
                    }
                }
                else 
                {
                    rsult.Code = ErrorCode.CommonError;
                    rsult.Description ="解析token出错";
                }
               

            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }

        public static bool IsDeviceExits(string _uuid) 
        {
            bool IsExits=false;
            try
            {
                string _addSql = SqlsControl.GetTargetDevice(_uuid);
                var result = SqlModel.ExecuteQuery(_addSql);
                IList<DeviceManagerModel> resultList = ModelConvertHelper<DeviceManagerModel>.ConvertToModel(result);
                IsExits = resultList.Count > 0 ? true : false;
            }
            catch (Exception ex) 
            {
            
            }
            return IsExits;
        }


        public static ResponseBody ToUpdateDevice(string _uuid,string _devicename, string _license, DateTime? _effecttime,string _token)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                var _Result = ApiActionAuth.OnAuthorization(_token);
                if (_Result.Code == ErrorCode.OK)
                {
                    UserModel itemUser = _Result.Data as UserModel;
                    string _addSql = SqlsControl.GetUpdateDevic(_uuid, _devicename, _license, _effecttime, itemUser.username);
                    var result = SqlModel.ExecuteNonQuery(_addSql);
                    if (result > 0)
                    {
                        rsult.Code = ErrorCode.OK;
                    }
                }
                else 
                {
                    rsult.Code = ErrorCode.CommonError;
                    rsult.Description = "解析token出错";
                }
               
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }

        public static ResponseBody ToDeleteTargetDevice(string _uuid)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _addSql = SqlsControl.GetDeleteDeviceByuuid(_uuid);
                var result = SqlModel.ExecuteNonQuery(_addSql);
                if (result > 0)
                {
                    rsult.Code = ErrorCode.OK;
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }

        public static ResponseBody ToGetAllDeviceByPage(int inputpageCode, int inputPageSize)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                var _itemResult = new ResulContentModel();
                string _AllCOuntSql = SqlsControl.GetDeviceAllCount();
                var _AlldataSet = SqlModel.ExecuteQuery(_AllCOuntSql);
                IList<DeviceManagerModel> resultList = ModelConvertHelper<DeviceManagerModel>.ConvertToModel(_AlldataSet);
                _itemResult.count= resultList.Count;
                //计算页数
                //if (resultList.Count % inputPageSize > 0)
                //{
                //    _itemResult.countPage = resultList.Count / inputPageSize + 1;
                //}
                //else
                //{
                //    _itemResult.countPage = resultList.Count / inputPageSize;
                //}




                string _Sql = SqlsControl.GetDeviceByPage(inputpageCode, inputPageSize);

                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                IList<DeviceManagerModel> resultPageList = ModelConvertHelper<DeviceManagerModel>.ConvertToModel(_dataSet);
                _itemResult.Items= resultPageList;
                if (resultList.Count > 0)
                {
                    rsult.Code = ErrorCode.OK;
                    rsult.Data = JsonConvert.SerializeObject(_itemResult).JsonFormatOut();
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToGetDeviceBySearch(string companyCode, string companyname, string robatmac, int inputpageCode, int inputPageSize)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {

                var _itemResult = new ResulContentModel();
                string _AllCOuntSql = SqlsControl.GetDeviceAllCountByCompanyId(companyCode, companyname, robatmac);
                var _AlldataSet = SqlModel.ExecuteQuery(_AllCOuntSql);
                IList<DeviceManagerModel> resultList = ModelConvertHelper<DeviceManagerModel>.ConvertToModel(_AlldataSet);
                _itemResult.count= resultList.Count;
            



                string _Sql = SqlsControl.GetDeviceByCompanyId(companyCode, companyname, robatmac, inputpageCode, inputPageSize);

                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                _itemResult.Items = ModelConvertHelper<DeviceManagerModel>.ConvertToModel(_dataSet);
                rsult.Code = ErrorCode.OK;
                rsult.Data = JsonConvert.SerializeObject(_itemResult).JsonFormatOut();
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }
        #endregion

        #region 设备模块
        public static ResponseBody ToAddDeviceModule(string _devieid,string _uuid, string _moduleid, string _modulename, string _version)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _addSql = SqlsControl.GetAddDevicModule(_devieid,_uuid, _moduleid, _modulename, _version);
                var result = SqlModel.ExecuteNonQuery(_addSql);
                if (result > 0)
                {
                    rsult.Code = ErrorCode.OK;
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }

        public static ResponseBody ToUpdateDeviceModule(List<DeviceModeuleManagerModel> itemsJson)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                if (itemsJson.Count > 0)
                {
                    string _macInfo = itemsJson.FirstOrDefault().deviceid;
                    string _itemSql = SqlsControl.GetTargetMacSql(_macInfo);
                    var resultTab = SqlModel.ExecuteQuery(_itemSql);
                    IList<DeviceManagerModel> resultList = ModelConvertHelper<DeviceManagerModel>.ConvertToModel(resultTab);
                    var _itemDev = resultList.FirstOrDefault();
                    if (_itemDev != null)
                    {
                        StringBuilder itemSql = new StringBuilder();
                        foreach (var item in itemsJson)
                        {
                            string _addSql = SqlsControl.GetUpdateDeviceModule(_itemDev.uuid, item.moduleid, item.clientversion);
                            itemSql.Append(_addSql);
                        }
                        var result = SqlModel.ExecuteNonQuery(itemSql.ToString());
                        if (result > 0)
                        {
                            rsult.Code = ErrorCode.OK;
                        }
                    }
                }
                else 
                {
                    rsult.Code = ErrorCode.OK;
                }
                  
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToDeleteDeviceModule(string _deviceid)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _isExitsSql = SqlsControl.GetDeviceModuledExits(_deviceid);
                var _dataSet = SqlModel.ExecuteQuery(_isExitsSql);
                IList<DeviceModeuleManagerModel> resultList = ModelConvertHelper<DeviceModeuleManagerModel>.ConvertToModel(_dataSet);
                if (resultList.Count > 0)
                {
                    string _addSql = SqlsControl.GetDeleteDeviceModuled(_deviceid);
                    var result = SqlModel.ExecuteNonQuery(_addSql);
                    if (result > 0)
                    {
                        rsult.Code = ErrorCode.OK;
                    }
                }
                else 
                {
                    rsult.Code = ErrorCode.OK;
                }

                
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToGetTargetModule(string _moduleid, string _version)
        {
            var itemResult = new ResponseBody();
            try
            {
                string _Sql = SqlsControl.GetTargetModule(_moduleid);

                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                IList<ModuleManagerModel> resultList = ModelConvertHelper<ModuleManagerModel>.ConvertToModel(_dataSet);
                if (resultList.Count > 0)
                {
                    var itemExits = resultList.FirstOrDefault();
                    if (itemExits != null) 
                    {
                        Version _newVersion = new Version(_version);
                        if (string.IsNullOrEmpty(itemExits.version))
                        {
                            itemResult.Code = ErrorCode.OK;
                        }
                        else 
                        {
                            Version _oldVersion = new Version(itemExits.version);
                            if (_newVersion.CompareTo(_oldVersion) > 0)
                            {
                                itemResult.Code = ErrorCode.OK;
                            }
                            else
                            {
                                itemResult.Code = ErrorCode.CommonError;
                                itemResult.Description = "只能上传比历史版本高的版本";
                            }
                        }
                      
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "ToGetTargetModule", ex.ToString());
                itemResult.Code = ErrorCode.CommonError;
                itemResult.Description = ex.Message;
            }
            return itemResult;
        }

        public static ResponseBody ToUpdateModule(string _moduleid, string _fileName,string _filePath,string _version)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _addSql = SqlsControl.GetUpdateModule(_moduleid, _fileName, _filePath, _version);
                var result = SqlModel.ExecuteNonQuery(_addSql);
                if (result > 0)
                {
                    rsult.Code = ErrorCode.OK;
                }
                else 
                {
                    rsult.Code = ErrorCode.CommonError;
                    rsult.Description = "系统错误，插入数据失败";
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToAddHistoryModule(string _moduleid,string _moduleName, string _fileName, string _filePath, string _version)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _uuid = Guid.NewGuid().ToString("N");
                string _addSql = SqlsControl.GetAddHistoryModuleSql(_uuid,_moduleid, _moduleName, _fileName, _filePath, _version);
                var result = SqlModel.ExecuteNonQuery(_addSql);
                if (result > 0)
                {
                    rsult.Code = ErrorCode.OK;
                }
                else
                {
                    rsult.Code = ErrorCode.CommonError;
                    rsult.Description = "系统错误，插入数据失败";
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToGetAuthorizeModuleByClient(string _robatmac)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _Sql = SqlsControl.GetTargetModuleByUpdate(_robatmac);
                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                var resultList = ModelConvertHelper<DeviceModeuleManagerModel>.ConvertToModel(_dataSet);
                rsult.Code = ErrorCode.OK;
                var ItemExits = resultList.FirstOrDefault();
                if (ItemExits!=null) 
                {
                    if (ItemExits.iscanupdate==1) 
                    {
                        rsult.Data = JsonConvert.SerializeObject(resultList).JsonFormatOut();
                    }
                }
               
                
            }
            catch (Exception ex)
            {

            }
            return rsult;
        }


        public static ResponseBody ToGetTargetModuleByClient(string _robatmac)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _Sql = SqlsControl.GetTargetModuleByUpdate(_robatmac);
                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                var resultList = ModelConvertHelper<DeviceModeuleManagerModel>.ConvertToModel(_dataSet);
                rsult.Code = ErrorCode.OK;
                if (resultList.Count > 0)
                {
                    var itemExits = resultList.FirstOrDefault();
                    if (itemExits.iscanupdate==1)
                    {
                        //var _effectList= resultList.Where(p=>!string.IsNullOrEmpty(p.version)).ToList();
                      
                        rsult.Data = JsonConvert.SerializeObject(resultList).JsonFormatOut();
                    }
                }
              
            }
            catch (Exception ex)
            {

            }
            return rsult;
        }

        public static ResponseBody ToGetTargetModuleByUpdate(string _robatmac) 
        {
            ResponseBody rsult = new ResponseBody();            
            try
            {
                string _Sql = SqlsControl.GetTargetModuleByUpdate(_robatmac);
                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                var resultList = ModelConvertHelper<DeviceModeuleManagerModel>.ConvertToModel(_dataSet);
                //var _effectList= resultList.Where(p=>!string.IsNullOrEmpty(p.version)).ToList();
                rsult.Code= ErrorCode.OK;
                rsult.Data=JsonConvert.SerializeObject(resultList).JsonFormatOut();
            }
            catch (Exception ex)
            {
               
            }
            return rsult;
        }

        public static ResponseBody ToGetHistoryModuleByPage(string moduleid, int inputpagecode, int inputpagesize)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _Sql = SqlsControl.GetHistoryModuleByPage(moduleid, inputpagecode, inputpagesize);
                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                var resultList = ModelConvertHelper<HistoryModuleManagerModel>.ConvertToModel(_dataSet);

                rsult.Code = ErrorCode.OK;
                rsult.Data = JsonConvert.SerializeObject(resultList).JsonFormatOut();
            }
            catch (Exception ex)
            {

            }
            return rsult;
        }

        #endregion


        public static bool InsertDeviceMac(string _MacInfo, string _encryinfo, string _CompanyName, DateTime _EffectTime,string DescripMsg) 
        {
            bool flg = false;
            try
            {
               
                string _checkExitsSql = SqlsControl.GetCheckMacExitsSql(_MacInfo);
                int _count = SqlModel.GetCommonDateCount(_checkExitsSql);
                if (_count > 0)
                {
                    //upodate
                    string _updateSql = SqlsControl.GetUpdateMacSql(_MacInfo, _encryinfo, _CompanyName, _EffectTime, DescripMsg);
                    var result = SqlModel.ExecuteNonQuery(_updateSql);
                    if (result>0)
                    {
                        flg = true;
                    }
                }
                
            }
            catch (Exception ex) 
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "InsertDeviceMac", ex.Message);
            }
            return flg;
        }


        public static ResponseBody GetTargetAuthorizationCode(string _macInfo)
        {
            CreatDb();
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _itemSql = SqlsControl.GetTargetMacSql(_macInfo);
                var resultTab = SqlModel.ExecuteQuery(_itemSql);
                IList<DeviceManagerModel> resultList = ModelConvertHelper<DeviceManagerModel>.ConvertToModel(resultTab);
                rsult.Code = ErrorCode.OK;
                rsult.Data = JsonConvert.SerializeObject(resultList).JsonFormatOut();
            }
            catch (Exception ex) 
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }


        public static ResponseBody ToAddOperationLog(string _robatmac,string _methodname)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                string _Sql = SqlsControl.GetTargetDeviceByrobatmac(_robatmac);

                var _dataSet = SqlModel.ExecuteQuery(_Sql);
                var _targetDevices = ModelConvertHelper<DeviceManagerModel>.ConvertToModel(_dataSet);
                if (_targetDevices.Count > 0)
                {
                    var _ItemDevice = _targetDevices.FirstOrDefault();
                    var _addItem = new LogManagerModel();
                    _addItem.uuid = Guid.NewGuid().ToString("N");
                    _addItem.companycode = _ItemDevice.companyid;
                    _addItem.companyname = _ItemDevice.companyname;
                    _addItem.robatmac = _robatmac;
                    _addItem.methodname = GetMethodChinesName(_methodname);
                    _addItem.count = 1;
                    var _nowTime = DateTime.Now;
                    _addItem.update_date = _nowTime;
                    _addItem.create_date = _nowTime;
                    string _LogAddSql = SqlsControl.GetAddLogSql(_addItem);
                    var result = SqlModel.ExecuteNonQuery(_LogAddSql);
                    if (result > 0)
                    {
                        rsult.Code = ErrorCode.OK;
                    }
                }
                else 
                {
                    rsult.Code = ErrorCode.CommonError;
                    rsult.Description = "为查询到对应的公司与设备信息";
                }
            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }

        private static string GetMethodChinesName(string key) 
        {
            string _name = key;
            switch (key) 
            {
                case ComnonStaticModel.ToGetNeedDownModule:
                    _name = "检查升级";
                    break;
                case ComnonStaticModel.ToDownloadTemplate:
                    _name = "更新文件";
                    break;
                case ComnonStaticModel.GetAuthorizationCode:
                    _name = "获取授权";
                    break;
            }
            return _name;
        }

        public static ResponseBody GetAllLogByPage(int inputpagecode, int inputpagesize)
        {
            ResponseBody rsult = new ResponseBody();
            try
            {
                var _itemResult = new ResulContentModel();
                string _AllCOuntSql = SqlsControl.GetAllLogSql();
                _itemResult.count = SqlModel.GetCommonDateCount(_AllCOuntSql); ;



                string _itemSql = SqlsControl.GetAllLogByPageSql(inputpagecode, inputpagesize);
                var resultTab = SqlModel.ExecuteQuery(_itemSql);
             
                _itemResult.Items = ModelConvertHelper<LogManagerModel>.ConvertToModel(resultTab);
                rsult.Code = ErrorCode.OK;
                rsult.Data = JsonConvert.SerializeObject(_itemResult).JsonFormatOut();


            }
            catch (Exception ex)
            {
                rsult.Code = ErrorCode.CommonError;
                rsult.Description = ex.Message;
            }
            return rsult;
        }
        #endregion
    }
}
